<template>
  <div class="front serve">
    <div class="header-box">
      <Header></Header>
    </div>
    <div class="shop-cart">
      <div class="content">
        <div class="con" v-if="cartList.length > 0">
          <div class="titl-wrapper clearfix">
            <div class="titl-item" style="width: 116px;box-sizing: border-box;text-align: left;">
              <el-checkbox v-model="allChecked" @change="handleSelectAllClassfiy">全选</el-checkbox>
            </div>
          </div>
          <ul class="product-list">
            <li class="product-item" v-for="(cartItem, firIndex) in cartList" :key="cartItem.id">
              <template v-if="cartItem.detailList.length > 0">
                <div class="seller"><span class="seller-name">
                    <el-checkbox v-model="cartItem.mychecked" @change="firstChanged(firIndex)">
                      店铺：{{cartItem.gongyingName}}</el-checkbox>
                  </span></div>
              </template>
              <div class="product-item-con clearfix" :class="{'on': product.mychecked}"
                v-for="(product, secIndex) in cartItem.detailList" :key="product.productId+secIndex">
                <div class="checkbox-wrapper">
                  <el-checkbox v-model="product.mychecked" @change="secondChanged(firIndex)"></el-checkbox>
                </div>
                <div class="product-infor clearfix">
                  <img :src="product.image" alt="">
                  <div class="text">
                    <div class="name">{{product.name}}</div>
                    <!--                      <div class="name" style="margin-top: 5px;">{{cartItem.speName}}</div>-->
                  </div>
                </div>
                <div class="specifications">规格：{{product.productSkuName}}</div>
                <div class="price">{{product.priceText}}</div>
                <!--                <div class="price">x{{product.num}}</div>-->
                <el-input-number size="mini" :min="1" :max="product.store" style="float: left;width: 95px;"
                  v-model="product.num" @change="productNumChange(product)"></el-input-number>
                <div class="total-price price">¥{{product.price*product.num | fixed}}</div>
                <div class="handle-wrapper">
                  <div class="btn" v-if="product.isCollect" @click="handleCollect(product)">取消收藏</div>
                  <div class="btn" v-else @click="handleCollect(product)">加入收藏夹</div>
                  <div class="btn" @click="handleDeletCart(1, product.cardId)">删除</div>
                </div>
              </div>
            </li>
          </ul>
          <div class="settlement-wrapper clearfix">
            <div class="all-wrapper">
              <el-checkbox v-model="allChecked" @change="handleSelectAllClassfiy">全选</el-checkbox>
            </div>
            <div class="delet-btn" v-if="submitFlag" @click="handleDeletCart(2)">删除</div>
            <!--            <div class="delet-btn" v-if="submitFlag" @click="deletChecked">加入收藏夹</div>-->
            <button type="button" class="settlement-btn" :disabled="!submitFlag || !submitFlag2"
              @click="toConfirmOrder">结算</button>
            <div class="total-amount">合计 <i>¥<span>{{totalAmount | fixed}}</span></i></div>
            <div class="num">已选择{{totalNum}}件商品</div>
          </div>
        </div>
        <div class="null-product" v-else>
          <div class="text">
            <div class="desc">您的购物车里什么也没有哦～</div>
            <div class="shopping" @click="$router.push({path: 'front-goodList?type=1'})">去逛逛 &gt;</div>
          </div>
        </div>
      </div>
    </div>
    <div class="footer">
      <Footer></Footer>
    </div>
  </div>
</template>

<script>
import { listMyCar, saveOrUpdate, removeByIds, collect } from "@/api/cart.js";
import Footer from "@/views/front/components/Footer";
import Header from "@/views/front/components/Header";
export default {
  data() {
    return {
      cartList: [],
      submitFlag2: true
    };
  },
  created() {
    this.getCart()
  },
  destroyed() {
  },
  components: {
    Footer,
    Header
  },
  filters: {
    fixed: function (value) {
      return value.toFixed(2)
    }
  },
  computed: {
    allChecked: {
      get() {
        let count = 0;
        for (let i = 0; i < this.cartList.length; i += 1) {
          if (this.cartList[i].mychecked === true) {
            count += 1;
          } else {
            count -= 1;
          }
        }
        if (count === this.cartList.length) {
          return true;
        }
        return false;
      },
      set(val) {
        return val;
      }
    },
    checkedProducts: {
      get() {
        let checkedProduct = []
        for (let i = 0; i < this.cartList.length; i++) {
          for (let j = 0; j < this.cartList[i].detailList.length; j++) {
            if (this.cartList[i].detailList[j].mychecked === true) {
              checkedProduct.push(this.cartList[i].detailList[j])
            }
          }
        }
        return checkedProduct;
      },
      set(val) {
        return val;
      }
    },
    submitFlag: {
      get() {
        return this.checkedProducts.length;
      },
      set(val) {
        return val;
      }
    },
    totalNum: {
      get() {
        let count = 0;
        for (let j = 0; j < this.checkedProducts.length; j++) {
          if (this.checkedProducts[j].mychecked) {
            count += this.checkedProducts[j].num
          }
        }
        return count;
      },
      set(val) {
        return val;
      }
    },
    totalAmount: {
      get() {
        let totalAmount = 0;
        for (let j = 0; j < this.checkedProducts.length; j++) {
          if (this.checkedProducts[j].mychecked) {
            totalAmount += Number((this.checkedProducts[j].num * this.checkedProducts[j].price).toFixed(2))
          }
        }
        return totalAmount;
      },
      set(val) {
        return val;
      }
    },
  },
  watch: {
  },
  methods: {
    productNumChange(v) {
      console.log(v)
      this.submitFlag2 = false
      const data = {
        gongyingId: v.gongyingId,
        num: v.num,
        productId: v.productId,
        productSkuId: v.productSkuId
      }
      if (v.timer) clearTimeout(v.timer)
      v.timer = setTimeout(() => {
        saveOrUpdate(data).then(respanse => {
          this.submitFlag2 = true
        }).catch(err => {
          this.submitFlag2 = true
        })
      }, 500)
    },
    // 删除商品
    handleDeletCart(type, cardId) {
      if (type == 1) {
        let data = {
          cartIds: cardId
        }
        removeByIds(data).then(respanse => {
          for (let i = 0; i < this.cartList.length; i++) {
            for (let j = 0; j < this.cartList[i].detailList.length; j++) {
              if (this.cartList[i].detailList[j].cardId == cardId) {
                this.cartList[i].detailList.splice(j, 1)
                if (this.cartList[i].detailList.length <= 0) {
                  this.cartList.splice(i, 1)
                }
              }
            }
          }
        })
      } else {
        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let cartIds = []
          for (let j = 0; j < this.checkedProducts.length; j++) {
            if (this.checkedProducts[j].mychecked) {
              cartIds.push(this.checkedProducts[j].cardId)
            }
          }
          let data = {
            cartIds: cartIds.join(',')
          }
          removeByIds(data).then(respanse => {
            this.getCart()
          })
        }).catch(() => {
        });
      }
    },
    // 收藏/取消商品
    handleCollect(item) {
      let data = {
        otherId: item.productId,
        type: 1
      }
      collect(data).then(respanse => {
        item.isCollect = !item.isCollect
      })
    },
    //  获取购物车
    getCart() {
      listMyCar().then(respanse => {
        const { countDTOS } = respanse
        if (countDTOS) {
          countDTOS.forEach(item => {
            this.$set(item, 'mychecked', false);
            item.detailList.forEach(e => {
              this.$set(e, 'timer', null);
            })
          })
          this.cartList = countDTOS
        } else {
          this.cartList = []
        }
      })
    },
    // 一级change事件
    firstChanged(index) {
      const { detailList } = this.cartList[index];
      if (this.cartList[index].mychecked === false) {
        detailList.forEach((item) => {
          this.$set(item, 'mychecked', false);
        });
      } else {
        detailList.forEach((item) => {
          this.$set(item, 'mychecked', true);
        });
      }
    },
    // 二级change事件
    secondChanged(index) {
      const subData = this.cartList[index].detailList;
      let tickCount = 0;
      const len = subData.length;
      for (let i = 0; i < len; i += 1) {
        if (subData[i].mychecked === true) {
          tickCount += 1;
        } else {
          tickCount -= 1;
        }
      }
      if (tickCount === len) {
        // 二级全勾选  一级勾选
        this.$set(this.cartList[index], 'mychecked', true);
      } else {
        // 二级未全选  一级不勾选
        this.$set(this.cartList[index], 'mychecked', false);
      }
    },
    // 总的全选
    handleSelectAllClassfiy(val) {
      if (val) {
        for (let i = 0; i < this.cartList.length; i += 1) {
          this.cartList[i].mychecked = true;
          this.firstChanged(i); // 调用一级change事件
        }
      } else {
        for (let i = 0; i < this.cartList.length; i += 1) {
          this.cartList[i].mychecked = false;
          this.firstChanged(i); // 调用一级change事件
        }
      }
    },
    toConfirmOrder() {
      let cartIds = []
      for (let j = 0; j < this.checkedProducts.length; j++) {
        if (this.checkedProducts[j].mychecked) {
          cartIds.push(this.checkedProducts[j].cardId)
        }
      }
      console.log(cartIds);
      this.$router.push({ path: '/confirm-order', query: { cartIds: cartIds.join(',') } })
    }
  },
};
</script>
<style>
.shop-cart .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #952825;
  border-color: #952825;
}
.shop-cart .el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #952825;
  border-color: #952825;
}
.shop-cart .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #333;
}
</style>
<style lang="scss" scoped>
.clearfix:after {
  content: "";
  display: block;
  clear: both;
}
.clearfix {
  zoom: 1;
}
.shop-cart {
  margin: 10px auto 0;
  width: 1200px;
}
.shop-cart .content {
  padding: 8px 0 38px;
  background-color: #fff;
}
.shop-cart .product-list {
  min-height: 317px;
}
.shop-cart .content .titl-wrapper {
  height: 49px;
  line-height: 49px;
  text-align: center;
  font-size: 14px;
  color: #333333;
}
.shop-cart .content .titl-wrapper .titl-item {
  float: left;
}
.shop-cart .content .product-item {
  margin-bottom: 20px;
}
.shop-cart .notice-text {
  text-align: right;
  font-size: 0;
}
.shop-cart .notice-text span {
  display: inline-block;
  vertical-align: top;
  padding: 7px 0 7px 25px;
  line-height: 16px;
  font-size: 12px;
  /*background: url("../confirm-order/notice.png") no-repeat left center;*/
  color: #e85514;
}
.shop-cart .content .product-item .seller {
  padding-left: 15px;
  line-height: 55px;
  font-size: 14px;
  color: #333333;
}
.shop-cart .content .product-item .seller .seller-name {
  /*margin-left: 10px;*/
}
.shop-cart .content .product-item .product-item-con {
  padding: 25px 0 25px 15px;
  margin-bottom: 5px;
  box-sizing: border-box;
  border: 1px solid #dedede;
  display: flex;
  align-items: center;
}
.shop-cart .content .product-item .product-item-con.on {
  background-color: #fff6f7;
}
.shop-cart .content .product-item:first-child {
  margin-top: 0;
}
.shop-cart .content .product-item .checkbox-wrapper {
  width: 55px;
  box-sizing: border-box;
}
.shop-cart .content .product-item .product-infor {
  width: 340px;
}
.shop-cart .content .product-item .product-infor img {
  display: block;
  width: 82px;
  height: 82px;
}
.shop-cart .content .product-item .product-infor .text {
  margin-left: 10px;
  width: 248px;
}
.shop-cart .content .product-item .text .name {
  line-height: 20px;
  font-size: 14px;
  color: #333333;
}
.shop-cart .content .product-item .specifications {
  width: 220px;
  margin-left: 10px;
  line-height: 20px;
  font-size: 14px;
  color: #333333;
}
.product-item .price {
  width: 106px;
  margin-left: 10px;
  line-height: 20px;
  font-size: 14px;
  font-weight: bold;
  color: #333333;
  word-break: break-all;
}
.product-item .total-price {
  margin-left: 26px;
  width: 170px;
  color: #952823;
  word-break: break-all;
}
.shop-cart .content .product-item .num {
  float: left;
  width: 182px;
  line-height: 22px;
  text-align: center;
  font-size: 14px;
  color: #333333;
}
.shop-cart .content .product-item .handle-wrapper {
  float: left;
  width: 130px;
}
.shop-cart .content .product-item .handle-wrapper .btn {
  line-height: 20px;
  font-size: 14px;
  color: #333333;
  cursor: pointer;
}
.shop-cart .content .product-item .handle-wrapper .btn:hover {
  text-decoration: underline;
}
.shop-cart .content .settlement-wrapper {
  height: 55px;
  background-color: #e5e5e5;
}
.shop-cart .content .settlement-wrapper .all-wrapper {
  float: left;
  padding-left: 13px;
  width: 116px;
  box-sizing: border-box;
  line-height: 55px;
}
.shop-cart .content .settlement-wrapper .delet-btn {
  float: left;
  padding: 0 10px;
  margin-left: 12px;
  line-height: 55px;
  font-size: 14px;
  color: #333333;
  cursor: pointer;
}
.shop-cart .content .settlement-wrapper .num {
  float: right;
  line-height: 55px;
  font-size: 14px;
  color: #333333;
}
.shop-cart .content .settlement-wrapper .num i {
  margin: 0 3px;
}
.shop-cart .content .settlement-wrapper i {
  font-size: 18px;
  color: #dd0b0b;
}
.shop-cart .content .settlement-wrapper .total-amount {
  float: right;
  margin-left: 20px;
  line-height: 55px;
  font-size: 14px;
  color: #333333;
}
.shop-cart .content .settlement-wrapper .total-amount i {
  color: #952825;
  font-style: normal;
}
.shop-cart .content .settlement-wrapper .total-amount span {
  display: inline-block;
  vertical-align: top;
  font-size: 26px;
}
.shop-cart .content .settlement-wrapper .settlement-btn {
  float: right;
  margin-left: 30px;
  width: 115px;
  height: 55px;
  line-height: 55px;
  text-align: center;
  font-size: 16px;
  background: #952825;
  color: #fff;
  cursor: pointer;
  border: none;
  outline: none;
}
.shop-cart .content .con {
  min-height: 440px;
}
.shop-cart .content .null-product {
  padding-top: 178px;
  height: 440px;
  box-sizing: border-box;
  text-align: center;
  font-size: 0;
}
.shop-cart .content .null-product .icon {
  display: inline-block;
  vertical-align: middle;
  width: 122px;
  height: 98px;
}
.shop-cart .content .null-product .text {
  display: inline-block;
  vertical-align: middle;
  margin-left: 42px;
  text-align: center;
}
.shop-cart .content .null-product .text .desc {
  line-height: 20px;
  font-size: 14px;
  color: #333333;
}
.shop-cart .content .null-product .text .shopping {
  margin-top: 17px;
  line-height: 24px;
  font-size: 16px;
  color: #e85514;
  text-decoration: underline;
  cursor: pointer;
}
button[disabled] {
  background-color: #999 !important;
  cursor: not-allowed !important;
}
</style>
